package com.smile.frame.config.log.systemlog;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.smile.frame.common.exception.BaseErrorCodeEnum;
import com.smile.frame.common.result.Result;
import com.smile.frame.common.util.LocalHttpUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * controller层系统日志处理
 *
 * @author Xy.wang
 * @date 2021/7/22 15:12

 */
@Slf4j
public class ControllerLogHandler extends AbstractHandlerLogger {

    public ControllerLogHandler(String methodName, Object response, SystemLog systemLog, Date startTime, Date endTime,
                                Object[] methodParams, Exception exception) {
        super(methodName, response, systemLog, startTime, endTime, methodParams, exception);
    }

    @Override
    public void outPutLogger() throws Throwable {
        StringBuilder sb = new StringBuilder();

        HttpServletRequest request = LocalHttpUtil.getRequest();
        // 处理请求参数
        sb.append("\n");
        sb.append("<===================================================").append("\n");
        sb.append("[request url ]:").append(request.getRequestURL()).append("\n");
        if (systemLog.show_req_body()) {
            sb.append("[request body ]:").append(JSONUtil.toJsonStr(methodParams)).append("\n");
        } else {
            sb.append("	[request body]:").append("not show").append("\n");
        }
        sb.append("[request time]:").append(DateUtil.format(startTime, DatePattern.NORM_DATETIME_MS_PATTERN)).append("\n");

        if (exception != null) {
            sb.append("**********************************异常*************************************").append("\n");
            log.error(sb.toString(), exception);
            sb.append("===================================================>").append("\n");
            throw exception;
        } else {
            //处理返回参数
            Result result = (Result) response;
            if (systemLog.show_resp_body()) {
                sb.append("[response body]: ").append(JSONUtil.toJsonStr(result)).append("\n");
            } else {
                sb.append("[response body]: null").append("\n");
            }

            sb.append("[response time]:").append(DateUtil.format(endTime, DatePattern.NORM_DATETIME_MS_PATTERN)).append("\n");
            sb.append("[consume time]:").append(DateUtil.between(startTime, endTime, DateUnit.MS)).append("ms").append("\n");
            sb.append("===================================================>").append("\n");
            //输出日志
            if (!result.getCode().equals(BaseErrorCodeEnum.BASE_SUCCESS.getCode())) {
                log.error(sb.toString());
            } else {
                log.info(sb.toString());
            }
        }

    }

}
